package webmarket.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import webmarket.common.CommonMethods;
import webmarket.jpacontrollers.UserJpaController;
import webmarket.model.User;

@Controller
@RequestMapping("/profile")
public class ProfileController extends ControllerBase {

	@RequestMapping
	public ModelAndView profile(ModelMap model) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		model.put("currentUser", true);
		// Must be authenticated, else can not reach this URL
		return profile(model, authentication.getName());
	}

	@RequestMapping("/{username}")
	public ModelAndView profile(ModelMap model, @PathVariable String username) {
		UserJpaController ujc = new UserJpaController();
		User user;
		user = ujc.getByUsername(username);
		if (user == null) {
			// User does not exist
			return new ModelAndView("redirect:/error/" + ErrorController.ErrorTypes.UserNotExists, model);
		}
		model.put("currentUserCity", ujc.getCurrent().getCity());
		model.put("user", user);
		return new ModelAndView("profile", model);
	}

	@RequestMapping(method = RequestMethod.POST)
	public String editProfile(@RequestParam(value = "edit_userid") int userId,
			@RequestParam(value = "edit_firstname") String firstname,
			@RequestParam(value = "edit_lastname") String lastname,
			@RequestParam(value = "edit_city") String city,
			@RequestParam(value = "edit_address") String address,
			@RequestParam(value = "edit_password", required=false, defaultValue="") String password) {
		UserJpaController ujc=new UserJpaController();
		User user=ujc.find(userId);
		if (user.getUsername().equals(CommonMethods.getCurrentUserName())){
			user.setFirstname(firstname);
			user.setLastname(lastname);
			user.setCity(city);
			user.setAddress(address);
			if (!!StringUtils.isBlank(password)){
				String encodedPassword = DigestUtils.sha1Hex(password);
				user.setPassword(encodedPassword);
			}
			ujc.edit(user);
		} else {
			return "redirect:/error/" + ErrorController.ErrorTypes.UserNotExists;
		}
		return "redirect:/profile";
	}
}
